import { getDistrctJson, getMyCityListApi } from '@/api/global'
import { deepClone } from '@/utils/index'

const useGlobalStore = defineStore('global', {
  state: () => ({
    district: [],
    myCityList: []
  }),
  getters: {
    citys: (state) => {
      let data = []
      if (state.district?.length) {
        const arr = deepClone(state.district)
        arr.map((item) => {
          item.children?.map((_item) => {
            _item.children = null
          })
        })

        data = arr
      }
      return data
    }
  },
  actions: {
    getDistrict() {
      return new Promise((resolve, reject) => {
        if (this.district.length) resolve()
        else {
          getDistrctJson()
            .then((res) => {
              this.district = res?.data ?? []
              resolve()
            })
            .catch((error) => {
              reject(error)
            })
        }
      })
    },
    /**获取账号下的城市列表 */
    getMyCityList() {
      return new Promise((resolve, reject) => {
        getMyCityListApi()
          .then((res) => {
            this.myCityList = res?.data ?? []
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    }
  }
})

export default useGlobalStore
